package com.sprouts.imagepicker.utils

import android.R
import android.app.Activity
import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener

/**
 * @Description TODO
 * @Author Clark
 * @CreateTime 2024年12月04日 15:57:15
 */
class NavigationBarChangeListener(private val rootView: View, private val orientation: Int) :
    OnGlobalLayoutListener {
    private val rect = Rect()
    private var isShowNavigationBar = false
    private var listener: OnSoftInputStateChangeListener? = null

    override fun onGlobalLayout() {
        rect.setEmpty()
        rootView.getWindowVisibleDisplayFrame(rect)
        var heightDiff = 0
        if (orientation == ORIENTATION_VERTICAL) {
            heightDiff = rootView.height - (rect.bottom - rect.top)
        } else if (orientation == ORIENTATION_HORIZONTAL) {
            heightDiff = rootView.width - (rect.right - rect.left)
        }
        val navigationBarHeight = if (Utils.hasVirtualNavigationBar(
                rootView.context
            )
        ) Utils.getNavigationBarHeight(
            rootView.context
        ) else 0
        if (heightDiff >= navigationBarHeight && heightDiff < navigationBarHeight * 2) {
            if (!isShowNavigationBar && listener != null) {
                listener!!.onNavigationBarShow(orientation, heightDiff)
            }
            isShowNavigationBar = true
        } else {
            if (isShowNavigationBar && listener != null) {
                listener!!.onNavigationBarHide(orientation)
            }
            isShowNavigationBar = false
        }
    }

    fun setListener(listener: OnSoftInputStateChangeListener?) {
        this.listener = listener
    }

    interface OnSoftInputStateChangeListener {
        fun onNavigationBarShow(orientation: Int, height: Int)

        fun onNavigationBarHide(orientation: Int)
    }

    companion object {
        const val ORIENTATION_VERTICAL: Int = 1 //监听竖屏模式导航栏的显示和隐藏
        const val ORIENTATION_HORIZONTAL: Int = 2 //监听横屏模式导航栏的显示和隐藏

        @JvmStatic
        fun with(activity: Activity): NavigationBarChangeListener {
            return with(activity.findViewById<View>(R.id.content), ORIENTATION_VERTICAL)
        }

        @JvmOverloads
        fun with(
            rootView: View,
            orientation: Int = ORIENTATION_VERTICAL
        ): NavigationBarChangeListener {
            val changeListener = NavigationBarChangeListener(rootView, orientation)
            rootView.viewTreeObserver.addOnGlobalLayoutListener(changeListener)
            return changeListener
        }

        @JvmStatic
        fun with(activity: Activity, orientation: Int): NavigationBarChangeListener {
            return with(activity.findViewById<View>(R.id.content), orientation)
        }


    }
}

